/**
 * 单链表相关操作
 * Created by Joy on 2024/7/22.
*/

#include "iostream"
using namespace std;

class MyLinkedList{

public:
    struct LinkedNode{
        int data;
        LinkedNode * next;
        LinkedNode(int data):data(data),next(NULL){};
    };
    //1.初始化
    void InitLinkedNode(){
        L = new LinkedNode(0);
        size = 0;
    }
    //2.头插法插入元素
    void InsertAtHead(int data){
        LinkedNode *node = new LinkedNode(data);
        node->next = L->next;
        L->next = node;
        size++;
    }
    //3.尾插法插入元素
    void InsertAtTail(int data){
        LinkedNode *node = new LinkedNode(data);
        LinkedNode *p = L;
        while (p->next){ //想图形，下一个为空就不循环
            p = p->next;
        }
        p->next = node;
        size++;
    }
    //4.指定位置添加
    void InsertAtIndex(int index,int data){
        if(index >size) return;
        if (index < 0) index = 0;
        LinkedNode *p = L;
        while (index--){  //定位指定索引
            p = p->next;
        }
        LinkedNode *node = new LinkedNode(data);
        node->next = p->next;
        p->next = node;
        size++;
    }
    //5.指定索引删除
    void DeleteData(int index){
        if(index >= size || index < 0) return;
        LinkedNode *p = L;
        LinkedNode *temp = NULL;
        while (index--){ //定位元素找到，索引前一个地址
            p = p->next;
        }
        temp = p->next;
        p->next = temp->next;
        delete temp;
        temp = NULL;
        size--;
    }
    //6.根据索引查找查找
    int get(int index){
        if (index>size ||index < 0 ) return -1;
        LinkedNode *p = L;
        while (index--){
            p = p->next;
        }
        return p->next->data;
    }
    //7.打印链表
    void PrintLinkedNode(){
        LinkedNode *p = L->next;
        while (p){
            cout << p->data << " ";
            p = p->next;
        }
        cout << endl;
    }
private:
    int size;
    LinkedNode * L;
};


int main() {

    MyLinkedList linkedList;
    linkedList.InitLinkedNode();
    for (int j = 0; j < 10; ++j) {
        linkedList.InsertAtHead(j);
    }
    cout << "头插法插入: ";
    linkedList.PrintLinkedNode();

    for (int j = 0; j < 10; ++j) {
        linkedList.InsertAtTail(j);
    }
    cout << "尾插法插入: " ;
    linkedList.PrintLinkedNode();

    cout << "指定索引9，删除0后：";
    linkedList.DeleteData(9);
    linkedList.PrintLinkedNode();

    cout << "根据索引查找最后一个元素：" << linkedList.get(18);

}
